<?php

namespace App\Http\Controllers\Admin\Ad;

use App\Models\Ad\AdvertNode;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class AdvertNodeController extends Controller
{
   /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
   public function index(Request $request)
   {
      $where = function ($query) use ($request) {
         if ($request->has('keyword') && $request->keyword != '') {
            $cate = $request->cate;
            $search = "%" . $request->keyword . "%";
            $query->where($cate, 'like', $search);
         }
      };

      $advert_nodes = DB::table('advert_nodes')
         ->where($where)
         ->orderByDesc('sort_order')
         ->get();

      return response()->json($advert_nodes);
   }

   /**
    * Store a newly created resource in storage.
    *
    * @param \Illuminate\Http\Request $request
    * @return \Illuminate\Http\Response
    */
   public function store(Request $request)
   {
      $advert_node = AdvertNode::create($request->all());
      if ($advert_node) {
         $info = ['status' => 1, 'msg' => '新增广告分类成功~'];
         return response()->json($info);
      }
   }

   /**
    * Display the specified resource.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function show($id)
   {
      $advert_node = AdvertNode::find($id);
      return response()->json($advert_node);
   }

   /**
    * Update the specified resource in storage.
    *
    * @param \Illuminate\Http\Request $request
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function update(Request $request, $id)
   {
      $advert_node = AdvertNode::find($id);
      $advert_node->update($request->all());
   }

   /**
    * Remove the specified resource from storage.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function destroy($id)
   {
      $info = ['status' => 1, 'msg' => '删除成功~'];
      //判断分类下是否有广告
      $advert_node = AdvertNode::check_adverts($id);
      if (!$advert_node) {
         $info = ['status' => 0, 'msg' => '此分类下有广告~'];
      }
      if ($info['status'] == 1) {
         AdvertNode::destroy($id);
      }
      return response()->json($info);
   }

   /***
    *  改变属性
    */
   public function change_attr(Request $request)
   {
      $advert_node = AdvertNode::find($request->id);
      $advert_node->is_show = $request->is_show == 1 ? false : true;
      $advert_node->save();
   }

   /***
    *  排序
    */
   public function change_sort(Request $request)
   {
      $advert_node = AdvertNode::find($request->id);
      $advert_node->sort_order = $request->sort_order;
      $advert_node->save();
   }

}
